package cnki.kg.demo.datatransfer;

import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Component
public class DataTransfer {

    public void execute(DataSourceItem sourceItem,DataSourceItem targetItem) throws SQLException, ClassNotFoundException {
        Connection sourceConn=null;
        Connection targetConn=null;
        try {
            Class.forName(targetItem.getDriverName());//指定连接类型
            targetConn = DriverManager.getConnection(targetItem.getUrl(), targetItem.getUser(), targetItem.getPassword());//获取连接
            Class.forName(sourceItem.getDriverName());//指定连接类型
            sourceConn = DriverManager.getConnection(sourceItem.getUrl(), sourceItem.getUser(), sourceItem.getPassword());//获取连接
            String sql = String.format("SELECT count(*) FROM %s ",sourceItem.getTableName());
            Integer totalCount = DataReader.executeScalar(sourceConn,sql);
            Integer pageSize = 500;
            int totalPage = totalCount / pageSize + ((totalCount % pageSize) == 0 ? 0 : 1);
            for (int pageIndex = 836; pageIndex <totalPage; pageIndex++) {
                List<Map<String, Object>> record = DataReader.readData(sourceConn,sourceItem.getDriverName(),sourceItem.getTableName(),pageIndex,pageSize);
                DataWriter.writeToMysql(targetConn,targetItem.getTableName(),record);
                System.out.printf("%s/%s\r\n",pageIndex+1,totalPage);
            }
        }catch (Exception ex){
            throw ex;
        }finally {
            if(sourceConn!=null){
                sourceConn.close();
            }
            if(targetConn!=null){
                targetConn.close();
            }
        }
    }
}
